<template>
  <div v-loading="loading">
    <el-row :gutter="10">
      <el-col style="text-align: left">
        <el-button
          type="success"
          @click="buttonClick.addBtnClick('D')"
        >新建部门</el-button>
        <el-button
          type="success"
          @click="buttonClick.addBtnClick('E')"
        >新建职员</el-button>
        <!-- <el-button
          type="primary"
          @click="buttonClick.openBtnClick(3)"
        >打开</el-button> -->
        <el-button
          type="danger"
          @click="buttonClick.deleteBtnClick()"
        >删除部门</el-button>
        <el-input
          style="display:inline;margin: 0px 12px"
          v-model="
          tableDatas.filters.searchText"
        >
          <template #prepend>搜索</template>
        </el-input>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <el-date-picker
              v-if="item.isDate"
              v-model="dialogDatas.currentData[item.value]"
              :type="item.dateOption ? item.dateOption.type : 'date'"
              :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
              :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
              :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
              :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
            />
            <el-switch
              v-else-if="item.isSwitch"
              v-model="dialogDatas.currentData[item.value]"
              inline-prompt
              active-text="启用"
              inactive-text="不启用"
              :active-value="item.trueValue"
              :inactive-value="item.falseValue"
            />
            <el-select
              v-else-if="item.isSelect"
              v-model="dialogDatas.currentData[item.value]"
              :disabled="item.disable"
              filterable
            >
              <el-option
                v-for="item in item.selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-input
              v-else
              v-model="dialogDatas.currentData[item.value]"
              :disabled="item.disable"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <el-row :gutter="10">
      <!-- 部门选择 -->
      <el-col :span="3">
        <el-card
          class="marginTop10"
          shadow="never"
        >
          <el-scrollbar max-height="85vh">
            <div
              v-for="dep in tableDatas.oriDepartmentData"
              style="text-align: left"
            >
              <el-radio
                v-model="tableDatas.filters.department"
                :value="dep['EMPLOYEEID']"
                size="large"
              >{{dep['EMP_NAME']}}</el-radio>
            </div>
          </el-scrollbar>

        </el-card>
      </el-col>
      <!-- 部门人员展示 -->
      <el-col :span="21">
        <el-table
          class="marginTop10"
          :data="tableDatas.tableDatasAfterPage"
          max-height="90vh"
          stripe
          border
          empty-text="无数据"
        >
          <el-table-column
            type="index"
            label="序号"
            align="center"
            width="60"
          />
          <el-table-column
            v-for="column in tableDatas.tableColumns"
            :prop="column.prop"
            :label="column.label"
            :align="column.align"
            :width="column.width"
          >
            <template
              #default="scope"
              v-if="column.prop =='EMP_TYPE'"
            >
              <div>
                <span v-show="scope.row['EMP_TYPE'] == 'A'">正式员工</span>
                <span v-show="scope.row['EMP_TYPE'] == 'T'">临时员工</span>
              </div>
            </template>

            <template
              #default="scope"
              v-if="column.prop =='operate'"
            >
              <div>
                <el-button
                  type="success"
                  @click="tableDatas.editBtnClick(scope.row)"
                >修改</el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="确定删除该条记录?"
                  @confirm="tableDatas.deleteBtnClick(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->
      </el-col>
    </el-row>

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';

import { v4 } from 'uuid';

import myAxios from '@/myAxios/myAxios';
import { showWarning } from '@/hooks/useMyMessageBox';
import store from '@/store';

export default {
  name: 'EmployeeAndDepartmentView',
  setup () {
    let loading = ref(false);
    let addBtnClick = function (EMP_CLASS) {
      let row = {
        'EMPLOYEEID': v4(),
        'EMP_CLASS': EMP_CLASS,
        'EMP_NAME': '',
        'EMP_NOTES': '',
        'EMP_DEPARTMENT': EMP_CLASS == 'E' ? tableDatas.filters.department : '',
        'EMP_TYPE': EMP_CLASS == 'E' ? 'A' : '',
        'isNew': true,
      };
      showFormDialog(row);
    };
    let deleteBtnClick = function () {
      if (tableDatas.oritableData.length) {
        showWarning('部门下仍有职员，请先删除职员');
        return;
      }
      else {
        if (tableDatas.filters.department) {
          let row = {
            'EMPLOYEEID': tableDatas.filters.department,
            'EMP_CLASS': 'D',
          };
          tableDatas.deleteBtnClick(row);
        }
      }
      // showFormDialog();
    };
    let buttonClick = {
      addBtnClick,
      deleteBtnClick,
    };

    let showFormDialog = function (row) {
      if (row.EMP_CLASS == 'D') {
        dialogDatas.formItems = dialogDatas.departFormItems;
      }
      else if (row.EMP_CLASS == 'E') {
        dialogDatas.formItems = dialogDatas.empFormItems;
      }
      if (!row.isNew) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
        let EMP_ID_Form_Item = dialogDatas.formItems.find(item => item.value == 'EMP_ID');
        EMP_ID_Form_Item.disable = true;
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = { ...row };
        let EMP_ID_Form_Item = dialogDatas.formItems.find(item => item.value == 'EMP_ID');
        EMP_ID_Form_Item.disable = false;
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
      ],
      departFormItems: [
        // {
        //   "value": "EMPLOYEEID",
        //   "label": "员工编号",
        //   "isDate": false,
        //   "disable":true,
        // },
        {
          "value": "EMP_ID",
          "label": "部门编号",
          "isDate": false,
          "disable": false,
        },
        {
          "value": "EMP_NAME",
          "label": "部门名称",
          "isDate": false,
          "disable": false,
        },
        {
          "value": "EMP_NOTES",
          "label": "备注",
          "isDate": false,
          "disable": false,
        },
        // {
        //   "value": "EMP_DEPARTMENT",
        //   "label": "部门",
        //   "isDate": false,
        //   "disable": false,
        //   "isSelect": true,
        //   "selectOptions": computed(() => {
        //     return tableDatas.oriDepartmentData.map(item => {
        //       return {
        //         value: item['EMPLOYEEID'],
        //         label: item['EMP_NAME'],
        //       };
        //     });
        //   }),
        // },
        // {
        //   "value": "EMP_CLASS",
        //   "label": "类型  D 部门  E 员工",
        //   "isDate": false,
        //   "disable":true,
        // },
        // {
        //   "value": "EMP_TYPE",
        //   "label": "类型",
        //   "isDate": false,
        //   "disable": false,
        //   "isSelect": true,
        //   "selectOptions": [
        //     {
        //       value: 'A',
        //       label: '正式员工',

        //     },
        //     {
        //       value: 'T',
        //       label: '临时员工',
        //     },
        //   ],
        // },
        // {
        //   "value": "DataVersion",
        //   "label": "版本号",
        //   "isDate": false,
        //   "disable":true,
        // },
        // {
        //   "value": "DEP_LEADER",
        //   "label": "部门领导",
        //   "isDate": false,
        //   "disable":true,
        // },
      ],
      empFormItems: [
        // {
        //   "value": "EMPLOYEEID",
        //   "label": "员工编号",
        //   "isDate": false,
        //   "disable":true,
        // },
        {
          "value": "EMP_ID",
          "label": "员工编号",
          "isDate": false,
          "disable": false,
        },
        {
          "value": "EMP_NAME",
          "label": "员工姓名",
          "isDate": false,
          "disable": false,
        },
        {
          "value": "EMP_NOTES",
          "label": "备注",
          "isDate": false,
          "disable": false,
        },
        {
          "value": "EMP_DEPARTMENT",
          "label": "部门",
          "isDate": false,
          "disable": false,
          "isSelect": true,
          "selectOptions": computed(() => {
            return tableDatas.oriDepartmentData.map(item => {
              return {
                value: item['EMPLOYEEID'],
                label: item['EMP_NAME'],
              };
            });
          }),
        },
        // {
        //   "value": "EMP_CLASS",
        //   "label": "类型  D 部门  E 员工",
        //   "isDate": false,
        //   "disable":true,
        // },
        {
          "value": "EMP_TYPE",
          "label": "类型",
          "isDate": false,
          "disable": false,
          "isSelect": true,
          "selectOptions": [
            {
              value: 'A',
              label: '正式员工',

            },
            {
              value: 'T',
              label: '临时员工',
            },
          ],
        },
        // {
        //   "value": "DataVersion",
        //   "label": "版本号",
        //   "isDate": false,
        //   "disable":true,
        // },
        // {
        //   "value": "DEP_LEADER",
        //   "label": "部门领导",
        //   "isDate": false,
        //   "disable":true,
        // },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   },
        //   "disable":true,
        // },
      ],
      confirmBtnClick: function () {
        loading.value = true;

        let EMPLOYEEID = dialogDatas.currentData.EMPLOYEEID;
        if (!EMPLOYEEID) {
          EMPLOYEEID = v4();
        }
        let EMP_CLASS = dialogDatas.currentData.EMP_CLASS;
        if (!EMP_CLASS) {
          showWarning('类型不能为空');
          return;
        }
        let isPass = dialogDatas.checkData(dialogDatas.currentData);
        if (!isPass) {
          return;
        }

        let DataVersion = dialogDatas.currentData.DataVersion ? dialogDatas.currentData.DataVersion++ : 1;
        let params = `${EMPLOYEEID}`
          + `🈹${dialogDatas.currentData.EMP_ID}`
          + `🈹${dialogDatas.currentData.EMP_NAME}`
          + `🈹${dialogDatas.currentData.EMP_NOTES}`
          + `🈹${dialogDatas.currentData.EMP_DEPARTMENT}`
          + `🈹${dialogDatas.currentData.EMP_CLASS}`
          + `🈹${dialogDatas.currentData.EMP_TYPE}`
          + `🈹${DataVersion}`
          + `🈹${dialogDatas.currentData.DEP_LEADER}`;

        let databaseAccount = store.state.databaseAccount;
        params += `🈹${databaseAccount}`;

        myAxios.post('WEB_MES_添加或修改人员信息', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            // ElMessage({
            //   showClose: true,
            //   type: 'success',
            //   message: '提交成功!' + res
            // });
            if (dialogDatas.currentData.EMP_CLASS == 'E') {
              getTableDatas(dialogDatas.currentData.EMP_DEPARTMENT);
            }
            else {
              getTableDatas();
            }
          }
          else {
            loading.value = false;
            showWarning('更新失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('更新失败err!' + err);
        });

      },
      checkData: function (row) {
        let EMP_ID = row.EMP_ID;
        if (!EMP_ID) {
          showWarning('编号不能为空');
          return false;
        }
        let EMP_NAME = row.EMP_NAME;
        if (!EMP_NAME) {
          showWarning('名称不能为空');
          return false;
        }
        // let EMP_NOTES = row.EMP_NOTES;
        // if (!EMP_NOTES) {
        //   showWarning('备注不能为空');
        //   return false;
        // }
        let EMP_CLASS = row.EMP_CLASS;
        if (EMP_CLASS == 'E') {
          let EMP_DEPARTMENT = row.EMP_DEPARTMENT;
          if (!EMP_DEPARTMENT) {
            showWarning('部门不能为空');
            return false;
          }
          let EMP_TYPE = row.EMP_TYPE;
          if (!EMP_TYPE) {
            showWarning('类型不能为空');
            return false;
          }
        }
        return true;
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = async function (department) {
      loading.value = true;
      if (!department) {
        let databaseAccount = store.state.databaseAccount;
        let params = `${databaseAccount}`;

        tableDatas.oriDepartmentData = await myAxios.get('WEB_MES_获取部门信息', params);
        tableDatas.filters.department = tableDatas.oriDepartmentData[0]['EMPLOYEEID'];
      }
      else {
        tableDatas.filters.department = department;
      }
      let params = `${tableDatas.filters.department}`;
      let databaseAccount = store.state.databaseAccount;
      params += `🈹${databaseAccount}`;

      myAxios.get('WEB_MES_获取部门人员信息', params).then(res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oritableData = [...res];
          // ElMessage({
          //   showClose: true,
          //   type: 'success',
          //   message: '最新数据获取成功!'
          // });
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });


    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',
        department: '',

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          let searchKeys = ['EMP_ID', 'EMP_NAME', 'EMP_NOTES'];
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        // {
        //   "prop": "EMPLOYEEID",
        //   "label": "员工编号",
        //   "align": "center",
        //   "width": 120,
        // },
        {
          "prop": "EMP_ID",
          "label": "员工编号",
          "align": "center",
          "width": 120,
        },
        {
          "prop": "EMP_NAME",
          "label": "员工姓名",
          "align": "center",
          "width": 120,
        },
        {
          "prop": "EMP_NOTES",
          "label": "备注",
          "align": "center"
        },
        // {
        //   "prop": "EMP_DEPARTMENT",
        //   "label": "所属部门的EMPLOYEEID",
        //   "align": "center",
        //   "width": 120,
        // },
        // {
        //   "prop": "EMP_CLASS",
        //   "label": "类型  D 部门  E 员工",
        //   "align": "center",
        //   "width": 120,
        // },
        {
          "prop": "EMP_TYPE",
          "label": "类型",
          "align": "center",
          "width": 100,
        },
        // {
        //   "prop": "DataVersion",
        //   "label": "版本号",
        //   "align": "center",
        //   "width": 120,
        // },
        // {
        //   "prop": "DEP_LEADER",
        //   "label": "部门领导",
        //   "align": "center",
        //   "width": 120,
        // },
        {
          "prop": "operate",
          "label": "操作",
          "align": "center",
          "width": 170,
        }
      ],
      oritableData: [],
      oriDepartmentData: [],
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;

        let params = `${row['EMPLOYEEID']}`;

        let databaseAccount = store.state.databaseAccount;
        params += `🈹${databaseAccount}`;

        myAxios.post('WEB_MES_删除人员/部门信息', params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            ElMessage({
              showClose: true,
              type: 'success',
              message: '删除成功!' + res
            });
            // 删除部门
            if (row['EMP_CLASS'] == 'D') {
              let index = tableDatas.oriDepartmentData.findIndex(item => item['EMPLOYEEID'] == row['EMPLOYEEID']);
              tableDatas.oriDepartmentData.splice(index, 1);
              tableDatas.filters.department = tableDatas.oriDepartmentData[index]['EMPLOYEEID'];
            }
            // 删除员工
            else if (row['EMP_CLASS'] == 'E') {
              tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
            }
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    watch(() => tableDatas.filters.department, (newVal, oldVal) => {
      getTableDatas(newVal);
    });

    return {
      loading,
      buttonClick,
      dialogDatas,
      tableDatas,
    };
  }
}
</script>
<style lang="css" scope>
.marginTop10 {
  margin-top: 10px;
}
</style>

